<template>
<div>
    <div class="head">
      <el-button :icon="Icon.Search" @click="showForm">应付单查询</el-button>
      <el-button :icon="Icon.Position" @click="payBatch">批量支付</el-button>
      <el-badge :is-dot="isDot" class="item">
       <el-button :icon="Icon.ChatDotRound" @click="showInvoice">供应商发票</el-button>
      </el-badge>


    </div>
  <el-dialog v-model="isShowForm"  class="formclass" draggable width="600px">
      <el-form
          :model="searchForm"
          label-width="100px"
      >
        <el-form-item label="购货单号" prop="financialOrderId">
          <el-input v-model="searchForm.financialOrderId" placeholder="请输入财务购货单号"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付类型" prop="payType">
              <el-select v-model="searchForm.payType" clearable="true" filterable fit-input-width="true" placeholder="请选择支付类型" prop="payType"
                         style="width: 145px" @change="getType">
                <el-option
                    v-for="item in payTypeValue"
                    :key="item"
                    :label="item.value"
                    :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
            <el-button @click="cancelExpert">取消</el-button>
            <el-button type="primary" @click="searchOk">确认</el-button>
        </span>
      </template>
    </el-dialog>

  <el-dialog v-model="isShow"  class="formclass" draggable width="600px">
    <div style="margin-left: 5px;margin-bottom: 6px">
          <span style="font-size: 15px">发票信息:</span>
    </div>
    <el-table :data="msgs" border>
      <el-table-column label="发票代码" prop="invoiceCode" width="190px"/>
      <el-table-column label="发票名称" prop="invoiceName" width="100px"/>
      <el-table-column label="开票日期" prop="createDate" width="100px"/>
       <el-table-column fixed="right" label="操作" prop="">
          <template #default="scope">
            <el-button  color="#97d578" plain  round size="default" @click="login(scope.row)">登记</el-button>
          </template>
        </el-table-column>
    </el-table>
  </el-dialog>

    <el-divider></el-divider>
    <el-scrollbar>
      <el-table ref="multipleTable"
                :data="tableData"
                border
                height="542px"
                row-style="height:50px"
                stripe style=" width: 100%"
                tooltip-effect="dark"
                @select="select"
                @selection-change="handleSelection">
        <el-table-column type="selection" :selectable="selectable" width="55"></el-table-column>
        <el-table-column :index="getIndex" label="序号" type="index" width="60"/>
        <el-table-column label="应付单号"  prop="payableOrderId" width="243"/>
        <el-table-column label="购货单号" prop="financialOrderId" width="243px"/>
        <el-table-column label="创建时间" prop="createdDate" width="175px"/>
        <el-table-column label="应付金额(单位:元)" prop="payableCost" width="139px"/>
        <el-table-column label="支付状态" prop="payType" width="118px"/>
        <el-table-column fixed="right" label="操作" prop="">
          <template #default="scope">
            <el-button  color="#97d578" plain  round size="default" @click="look(scope.row)">其他信息</el-button>
             <el-button  color="#97d578" plain  round size="default" @click="payOne(scope.row)">支付</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page=pageNow
          :page-size=pageSize
          :page-sizes="[10,20,30,40]"
          :total=totalSize
          background
          layout="total, prev, pager, next"
          style="margin-top: 15px"
          @current-change="pageChange"
      >
      </el-pagination>

      <el-dialog v-model="Visible" center title="其他信息" width="60%">
        <div style="margin-left: 5px;margin-bottom: 6px">
          <span style="font-size: 15px">商品信息:</span>
        </div>
        <el-table :data="rowData" border>
          <el-table-column label="商品代码" prop="goodId" width="190px"/>
          <el-table-column label="商品名称" prop="goodName" width="100px"/>
          <el-table-column label="数目" prop="goodCount" width="100px"/>
          <el-table-column label="单价(单位：元)" prop="price" width="120px"/>
        </el-table>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>

<script>
import Header from "@/components/Header";
import {MoreFilled,Search,Position,ChatDotRound} from "@element-plus/icons-vue";
import axios from "axios";
import {ElMessage, ElNotification} from "element-plus";
import store from "@/store";
export default {
name: "PayableOrderManage",
  data(){
    return{
      Icon:{Search,MoreFilled,Position,ChatDotRound},
      tableData:[
      ],
      rowData:[
      ],
      searchForm:{
        financialOrderId:'',
        payType:''
      },
      payTypeValue:[
        {code:'1',value:'未付款'},
        {code:'0',value:'已付款'}
      ],
      pageSize:10,
      totalSize:100,
      pageNow:1,
      Visible:false,
      multipleSelection:[],
      idList:[
      ],
      isShowForm:false,
      msg:{
        data:'',
        msg:''
      },
      isDot:false,
      isShow:false,
      msgs:[],
      path:'ws://localhost:1070/websocket/boyan'
    }
  },
  methods:{

    login(row){

      this.$axios.post("http://localhost:1070/invoice/register",{
        orderId:row.orderId,
        invoice:row.invoice,
        operationId:row.operationId
      }).then(res=>{
        res=res.data
        if (res.code == '200') {
          this.$message({
            type: 'success',
            message: '支付成功'
          });
          this.idList=[]
          this.multipleSelection = []
        }else if (res.code == '10012'){
          this.$message({
            type: 'warning',
            message: res.msg
          });
        }else {
          this.$message({
            type: 'error',
            message: '支付失败!'
          });
        }

      })

      this.loadPost()
    },
    showInvoice(){
      this.isShow = true
    },

    cancelExpert() {
      this.isShowForm = false
      ElNotification.success({
        title:'取消操作',
        offset: 100,
      })
      this.loadPost()
    },
    searchOk(){
      this.$axios.post("http://localhost:1070/payable",{
        pageNow:this.pageNow,
        pageSize:this.pageSize,
        financialOrderId:this.searchForm.financialOrderId,
        payType:this.searchForm.payType,
      }).then(res=>{
        res=res.data
        if (res.code == '200'){
          this.totalSize = res.data.totalRows
          this.tableData = res.data.rowData
          for (let i = 0;i<this.tableData.length;i++){
            this.tableData[i].select = false;
          }
          this.$message({
            type: 'success',
            message: '查询成功!'
          });
        }else {
          this.$message({
            type: 'error',
            message: '查询失败!'
          });
          this.tableData = []
          this.totalSize = 0
        }

      })
      this.isShowForm = false
    },
    showForm(){
      this.isShowForm = true
      this.searchForm = {
        financialOrderId:'',
        payType:''
      }
    },

  payBatch(){
    if (this.multipleSelection!=undefined&&this.multipleSelection.payableOrderId != undefined){
      this.pay(this.multipleSelection)
    }else {
      ElMessage('请先选择要修改的商品！')
    }

  },
  payOne(row){
    this.idList.push(row.payableOrderId)
    this.pay(this.idList)

  },
    getType(value){
      console.log(value)
      this.searchForm.payType = value
    },
    selectable(row){
      return row.payType !=='已付款'
    },
    handleSelection(selection){
    for(let i = 0;i<selection.length;i++){
      this.multipleSelection.push(selection[i].payableOrderId)
    }
    },
    pay(row){
      console.log(row)
      this.$axios.post("http://localhost:1070/payable/pay",{
        payableOrderId:row
      }).then(res=>{
        res=res.data
        if (res.code == '200') {
          this.$message({
            type: 'success',
            message: '支付成功'
          });
          this.idList=[]
          this.multipleSelection = []
        }else if (res.code == '10012'){
          this.$message({
            type: 'warning',
            message: res.msg
          });
        }else {
            this.$message({
              type: 'error',
              message: '支付失败!'
            });
          }

      })

      this.loadPost()
    },

    look(row){
      console.log(row)
      this.rowData = []
      this.rowData.push(row)
      this.Visible = true

    },
    getIndex(index){
      index = index + 1 + (this.pageNow - 1) * this.pageSize
      return index
    },
    pageChange(val){
      this.pageNow = val
      console.log(this.pageNow)
      this.$axios.post("http://localhost:1070/payable",{
        pageNow:this.pageNow,
        pageSize:this.pageSize,
      }).then(res=>{
        res=res.data
        if (res.code == '200') {
          this.totalSize = res.data.totalRows
          this.tableData = res.data.rowData
          for (let i = 0;i<this.tableData.length;i++){
            this.tableData[i].select = false;
          }
          console.log(res.data)
        }else {
          this.tableData = []
          this.totalSize = 0
        }

      })
    },
    loadPost(){
      this.$axios.post("http://localhost:1070/payable",{
        pageNow:this.pageNow,
        pageSize:this.pageSize
      }).then(res=>{
        res=res.data
        if (res.code == '200'){
          this.totalSize = res.data.totalRows
          this.tableData = res.data.rowData
          for (let i = 0;i<this.tableData.length;i++){
            this.tableData[i].select = false;
          }
          console.log(res.data)
        }else {
          this.tableData = []
          this.totalSize = 0
        }
      })
    },


    initWebSocket(){
      console.log('websocket连接了');
      //初始化weosocket
      this.websock = new WebSocket(this.path);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketsend(){//数据发送
      let msg=JSON.stringify(111111);
      this.websock.send(msg);
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      console.log("WebSocket连接成功");
    },
    websocketonerror(error){//连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e){ //数据接收
      console.log("接收数据了捏")
      var res = JSON.parse(e.data)
      if (res.msg == '连接成功'){
            ElNotification.success({
              title:res.msg,
              offset: 100,
            })
      }else if (res.msg == '您有新的采购发票待处理'){
        this.msg = res
        this.msgs.push(res)
        this.$store.commit('updateInvoiceMsgInfo', res);
      }

      console.log(this.msg)
    },
    websocketclose(e){  //关闭
      this.websock.close()
    },
    test(){
      this.websocketsend();
    }




  },

  computed:{
    //监听vuex的消息数据并返回给watch
    watchMyMessage(){
      return this.$store.state.InvoiceMsg.length
    }
  },
  watch:{

    watchMyMessage:{

      immediate:true,
      deep:true,
      handler:function (newVal,oldVal)  {

        if (newVal>oldVal){
          this.isDot = true
        }
        else{
          this.isDot = false
        }
      }
    }

  },


  beforeMount() {
    this.loadPost()
  },
  mounted(){
    this.initWebSocket()
  },
  beforeDestroy () {
    this.websocketclose()
  }
}
</script>

<style scoped>
body .el-table th.gutter {
  display: table-cell !important
}
.co1{
  background: #77c7d0;

}
.co2{
  background: #d9bf17;
}
.oo{
  background: #97d578
}
.formclass{
  border-radius: 20px;
}
.formclassTwo{
  border-radius: 20px;
}
.head{
  margin: 10px 0;
  text-align: left;
}
.item{
  margin-left: 14px;
}
</style>